package 多线程案例;

//模拟线程池
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;

class MyThreadPoolExecutor{
//    存放线程
    List<Thread> list = new ArrayList<>();
//    存放任务
    BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(100);
    MyThreadPoolExecutor(int n){
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(()->{
                //线程具体的工作
                while(true){
                    try {
                        //取出任务
                        //使用take方法，可以进入阻塞
                        Runnable x =  queue.take();
                        //执行任务
                        x.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

            });
            //将每一个线程都启动起来
            t.start();
            list.add(t);
        }
    }

    //添加任务
    public void submit(Runnable runnable) throws InterruptedException {
        //会进行唤醒操作
        queue.put(runnable);
    }
}
public class Demo_8 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoolExecutor executor = new MyThreadPoolExecutor(9);

        for (int i = 0; i < 1000; i++) {
            //此处i是变量不能打印出，需要变成常量
            int n = i;
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("线程名："+Thread.currentThread().getName()+"打印:"+n);
                }
            });
        }
    }
}
